<script setup>
//引入依赖
import Map from 'ol/Map';
import View from 'ol/View';
import VectorTileLayer from 'ol/layer/VectorTile';
import VectorTileSource from 'ol/source/VectorTile';
import MVT from 'ol/format/MVT';
import { onMounted, ref } from "vue";
import { fromLonLat } from "ol/proj";

const map = ref(null)
const info = ref(null)
const initMap = () => {
  map.value = new Map({
    target: 'map',
    layers: [
      //添加矢量瓦片类型图层
      new VectorTileLayer({
        source: new VectorTileSource({
          //设置矢量瓦片类型资源
          format: new MVT(),
          url: 'https://basemaps.arcgis.com/v1/arcgis/rest/services/World_Basemap/VectorTileServer/tile/{z}/{y}/{x}.pbf',
        }),
      })
    ],
    view: new View({
      // 经纬度转换
      center: fromLonLat([87.16552734375, 39.470125122358176]),
      zoom: 4,
      projection: "EPSG:3857", //指定投影
    })
  });

  map.value.on('pointermove',showInfo)
  function showInfo(event) {
    //获取到鼠标当前像素所获取到的要素
    const features = map.value.getFeaturesAtPixel(event.pixel);
    if (features.length === 0) {
      info.value.innerText = '';
      info.value.style.opacity = 0;
      return;
    }
    console.log(features);
    const properties = features[0].getProperties();
    info.value.innerText = JSON.stringify(properties, null, 2);
    info.value.style.opacity = 1;
  }
}


onMounted(initMap)
</script>

<template>
  <!--地图挂载dom-->
  <div id="map">
    <div id="info" ref="info"></div>
  </div>
</template>

<style scoped>
#map {
  width: 100%;
  height: 100%;
}
#info{
  position: absolute;
  top: 50px;
  right: 50px;
  color: red;
}
</style>